﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Transactions;
using System.Web.Services;

public partial class Main_Accounts_VoucherEntry_Sale : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    int ControlCounter = 2;
    string strsql = string.Empty;

    List<string> LstList;
    List<string> LstDrCr;
    List<string> LstLedgerName;
    List<string> LstDebit;
    List<string> LstCredit;
    List<string> LstBtn;
    List<string> LstHidAmt;
    List<string> LstBalance;

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        LstList = (List<string>)ViewState["LstList"];
        LstLedgerName = (List<string>)ViewState["LstLedgerName"];
        LstDrCr = (List<string>)ViewState["LstDrCr"];
        LstDebit = (List<string>)ViewState["LstDebit"];
        LstCredit = (List<string>)ViewState["LstCredit"];
        LstBtn = (List<string>)ViewState["LstBtn"];
        LstHidAmt = (List<string>)ViewState["LstHidAmt"];
        LstBalance = (List<string>)ViewState["LstBalance"];

        if (LstList != null)
        {
            int count = Convert.ToInt32(LstList.Count.ToString());

            for (int i = 0; i < count; i++)
            {
                ControlCounter++;

                Label lbl = new Label();
                lbl.ID = LstList[i].ToString();
                lbl.Text = ControlCounter.ToString();
                //Response.Write(" over lbl   " + lbl.ID.ToString() + "</Br>");
                HtmlTableRow htrow = new HtmlTableRow();


                HtmlTableCell htcell1 = new HtmlTableCell();
                htcell1.ID = "htcell1" + ControlCounter.ToString();
                htcell1.Width = "10%";
                htcell1.VAlign = "Top";
                DropDownList ddlDrCr = new DropDownList();
                ddlDrCr.ID = LstDrCr[i].ToString();
                //ddlDrCr.Items.Insert(0, new ListItem("", "0"));
                ddlDrCr.Items.Add(new ListItem("Dr", "1"));
                ddlDrCr.Items.Add(new ListItem("Cr", "2"));
                ddlDrCr.SelectedIndex = 0;
                ddlDrCr.Width = Unit.Percentage(98);
                ddlDrCr.AutoPostBack = true;
                ddlDrCr.ToolTip = "Debit/Credit";
                ddlDrCr.SelectedIndexChanged += new EventHandler(ddlDrCr_SelectedIndexChanged);
                ddlDrCr.CssClass = "dropdown";
                htcell1.Controls.Add(ddlDrCr);


                HtmlTableCell htcell2 = new HtmlTableCell();
                htcell2.ID = "htcell2" + ControlCounter.ToString();
                htcell2.Width = "30%";
                htcell2.VAlign = "Top";
                DropDownList ddlLedger = new DropDownList();
                ddlLedger.ID = LstLedgerName[i].ToString();
                ddlLedger.Width = Unit.Percentage(98);
                ddlLedger.AutoPostBack = true;
                ddlLedger.ToolTip = "Select Ledger for Transaction";
                ddlLedger.Attributes.Add("onchange", "return ValidateRepeatLedger(this.id);");
                ddlLedger.AutoPostBack = true;
                ddlLedger.SelectedIndexChanged += new EventHandler(ddlLedger_OnSelectedIndexChanged);
                ddlLedger.CssClass = "dropdown";
                htcell2.Controls.Add(ddlLedger);

                HtmlTableCell htcell3 = new HtmlTableCell();
                htcell3.ID = "htcell3" + ControlCounter.ToString();
                htcell3.Width = "20%";
                htcell3.VAlign = "Top";
                TextBox txtDebit = new TextBox();
                txtDebit.ID = LstDebit[i].ToString();
                txtDebit.Width = Unit.Percentage(98);
                txtDebit.ToolTip = "Debit Amount";
                txtDebit.Enabled = false;
                txtDebit.CssClass = "inputnumber";
                txtDebit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtDebit.Attributes.Add("onfocus", "return RemoveZeroOnFocusDebit(this.id);");
                txtDebit.Attributes.Add("onblur", "return SetZeroOnBlurDebit();");
                txtDebit.AutoCompleteType = AutoCompleteType.Disabled;
                htcell3.Controls.Add(txtDebit);


                HtmlTableCell htcell4 = new HtmlTableCell();
                htcell4.ID = "htcell4" + ControlCounter.ToString();
                htcell4.Width = "20%";
                htcell4.VAlign = "Top";
                TextBox txtCredit = new TextBox();
                txtCredit.ID = LstCredit[i].ToString();
                txtCredit.Width = Unit.Percentage(98);
                txtCredit.CssClass = "inputnumber";
                txtCredit.ToolTip = "Credit Amount";
                txtCredit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtCredit.Attributes.Add("onfocus", "return RemoveZeroOnFocusCredit(this.id);");
                txtCredit.Attributes.Add("onblur", "return SetZeroOnBlurCredit();");
                txtCredit.AutoCompleteType = AutoCompleteType.Disabled;
                htcell4.Controls.Add(txtCredit);

                HtmlTableCell htcell5 = new HtmlTableCell();
                htcell5.ID = "htcell5" + ControlCounter.ToString();
                htcell5.Width = "10px";
                htcell5.VAlign = "Top";
                Button btn = new Button();
                btn.ID = LstBtn[i].ToString();
                btn.Width = Unit.Percentage(98);
                btn.Text = "...";
                btn.CssClass = "button1";
                btn.ToolTip = "Bill Reference";
                btn.Attributes.Add("onclick", "return Transfervalue('" + ControlCounter + "');");
                // btn.OnClientClick = "alert('abc')";
                btn.Enabled = false;
                HiddenField hidbillamt = new HiddenField();
                hidbillamt.ID = LstHidAmt[i].ToString();
                htcell5.Controls.Add(hidbillamt);
                htcell5.Controls.Add(btn);

                HtmlTableCell htcell6 = new HtmlTableCell();
                htcell6.ID = "htcell6" + ControlCounter.ToString();
                htcell6.Width = "20%";
                htcell6.VAlign = "Top";
                TextBox txtBalance = new TextBox();
                txtBalance.ID = LstBalance[i].ToString();
                txtBalance.Width = Unit.Percentage(98);
                txtBalance.CssClass = "inputnumber";
                txtBalance.ToolTip = "Ledger Balance";
                txtBalance.Enabled = false;
                htcell6.Controls.Add(txtBalance);

                htrow.Cells.Add(htcell1);
                htrow.Cells.Add(htcell2);
                htrow.Cells.Add(htcell3);
                htrow.Cells.Add(htcell4);
                htrow.Cells.Add(htcell5);
                htrow.Cells.Add(htcell6);
                tblVouEntry.Rows.Add(htrow);

            }
        }


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {

            //**************Set Minimum and maximum date calender Control********
            AccountSettings.setMinMaxDate(form1);
            //********************End **********
            LstList = new List<string>();
            ViewState["LstList"] = LstList;

            LstDrCr = new List<string>();
            ViewState["LstDrCr"] = LstDrCr;

            LstLedgerName = new List<string>();
            ViewState["LstLedgerName"] = LstLedgerName;

            LstDebit = new List<string>();
            ViewState["LstDebit"] = LstDebit;

            LstCredit = new List<string>();
            ViewState["LstCredit"] = LstCredit;

            LstBtn = new List<string>();
            ViewState["LstBtn"] = LstBtn;

            LstHidAmt = new List<string>();
            ViewState["LstHidAmt"] = LstHidAmt;

            LstBalance = new List<string>();
            ViewState["LstBalance"] = LstBalance;
            BindVoucherNumber();
            txtDate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(System.DateTime.Now)).ToString();            
            BindLedger_ForDebitAndCredit(ddlDrCr1.SelectedIndex, 1);
            BindLedger_ForDebitAndCredit(ddlDrCr2.SelectedIndex, 2);


            if (Request.QueryString["status"] != null)
            {
                if (Request.QueryString["status"].ToString() == "save")
                {
                    lblMsg.Attributes.Add("class", "true");
                    lblMsg.Text = "Save Successfully....";

                }
            }
        }
    }
    protected void btnAddRow_Click(object sender, EventArgs e)
    {
        AddNewRow();
    }
    protected void btnDeleteRow_Click(object sender, EventArgs e)
    {
        DeleteLastRow();
    }

    protected void AddNewRow()
    {
        int flag = 0;
        int rowCount = Convert.ToInt32(hidControl.Value);
        //for (int i = 1; i < tblVouEntry.Rows.Count; i++)
        // {
        //    DropDownList ddlDrCr = (DropDownList)tblVouEntry.Rows[i].FindControl("ddlDrCr" + rowCount);
        //    DropDownList ddlLedger = (DropDownList)tblVouEntry.Rows[i].FindControl("ddlLedger" + rowCount);
        //    TextBox txtDebit = (TextBox)tblVouEntry.Rows[i].FindControl("txtDebit" + rowCount);
        //    TextBox txtCredit = (TextBox)tblVouEntry.Rows[i].FindControl("txtCredit" + rowCount);
        //    Button btn = (Button)tblVouEntry.Rows[i].FindControl("btn" + rowCount);

        //    TextBox txtBalance = (TextBox)tblVouEntry.Rows[i].FindControl("txtBalance" + rowCount);
        //    if ((ddlDrCr.SelectedIndex == 0) && (Convert.ToDouble(txtDebit.Text.ToString()) > 0))
        //    {
        //        flag = 1;

        //    }
        //    else if ((ddlDrCr.SelectedIndex == 1) && (Convert.ToDouble(txtCredit.Text.ToString()) > 0))
        //    {
        //        flag = 1;

        //    }
        //    if (ddlLedger.SelectedValue == "-1")
        //    {
        //        flag = 0;
        //    }

        //}
        //if (flag == 1)
        //{
        ControlCounter++;
        Label lbl = new Label();
        lbl.ID = "lbl" + ControlCounter.ToString();
        lbl.Text = ControlCounter.ToString();
        LstList.Add(lbl.ID);

        HtmlTableRow htrow = new HtmlTableRow();


        HtmlTableCell htcell1 = new HtmlTableCell();
        htcell1.ID = "htcell1" + ControlCounter.ToString();
        htcell1.Width = "10%";
        htcell1.VAlign = "Top";
        DropDownList ddlDrCr = new DropDownList();
        ddlDrCr.ID = "ddlDrCr" + ControlCounter.ToString();
        ddlDrCr.Width = Unit.Percentage(98);
        ddlDrCr.Items.Add(new ListItem("Dr", "1"));
        ddlDrCr.Items.Add(new ListItem("Cr", "2"));
        ddlDrCr.SelectedIndex = 0;
        //BindAllItemDropdownlist(dropdown);
        ddlDrCr.AutoPostBack = true;
        ddlDrCr.ToolTip = "Debit/Credit";
        ddlDrCr.SelectedIndexChanged += new EventHandler(ddlDrCr_SelectedIndexChanged);
        ddlDrCr.CssClass = "dropdown";
        htcell1.Controls.Add(ddlDrCr);
        LstDrCr.Add(ddlDrCr.ID);




        HtmlTableCell htcell2 = new HtmlTableCell();
        htcell2.ID = "htcell2" + ControlCounter.ToString();
        htcell2.Width = "30%";
        htcell2.VAlign = "Top";
        DropDownList ddlLedger = new DropDownList();
        ddlLedger.ID = "ddlLedger" + ControlCounter.ToString();
        ddlLedger.Width = Unit.Percentage(98);
        ddlLedger.CssClass = "dropdown";
        ddlLedger.ToolTip = "Select Ledger for Transaction";
        ddlLedger.Attributes.Add("onchange", "return ValidateRepeatLedger(this.id);");
        ddlLedger.AutoPostBack = true;
        ddlLedger.SelectedIndexChanged += new EventHandler(ddlLedger_OnSelectedIndexChanged);
        htcell2.Controls.Add(ddlLedger);
        LstLedgerName.Add(ddlLedger.ID);
        //Response.Write(ddlLedger.ID.ToString() + "</BR>");

        HtmlTableCell htcell3 = new HtmlTableCell();
        htcell3.ID = "htcell3" + ControlCounter.ToString();
        htcell3.Width = "20%";
        htcell3.VAlign = "Top";
        TextBox txtDebit = new TextBox();
        txtDebit.ID = "txtDebit" + ControlCounter.ToString();
        txtDebit.Width = Unit.Percentage(98);
        txtDebit.CssClass = "inputnumber";
        txtDebit.ToolTip = "Debit Amount";
        txtDebit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtDebit.Attributes.Add("onfocus", "return RemoveZeroOnFocusDebit(this.id);");
        txtDebit.Attributes.Add("onblur", "return SetZeroOnBlurDebit();");
        txtDebit.Text = "0.00";
        txtDebit.AutoCompleteType = AutoCompleteType.Disabled;
        htcell3.Controls.Add(txtDebit);
        LstDebit.Add(txtDebit.ID);




        HtmlTableCell htcell4 = new HtmlTableCell();
        htcell4.ID = "htcell4" + ControlCounter.ToString();
        htcell4.Width = "20%";
        htcell4.VAlign = "Top";
        TextBox txtCredit = new TextBox();
        txtCredit.ID = "txtCredit" + ControlCounter.ToString();
        txtCredit.Width = Unit.Percentage(98);
        txtCredit.CssClass = "inputnumber";
        txtCredit.ToolTip = "Credit Amount";
        txtCredit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtCredit.Attributes.Add("onfocus", "return RemoveZeroOnFocusCredit(this.id);");
        txtCredit.Attributes.Add("onblur", "return SetZeroOnBlurCredit();");
        txtCredit.Enabled = false;

        //txtCredit.Attributes.Add("onblur", "calcAmt();");
        txtCredit.AutoCompleteType = AutoCompleteType.Disabled;
        htcell4.Controls.Add(txtCredit);
        LstCredit.Add(txtCredit.ID);

        HtmlTableCell htcell5 = new HtmlTableCell();
        htcell5.ID = "htcell5" + ControlCounter.ToString();
        htcell5.Width = "10px";
        htcell5.VAlign = "Top";
        Button btn = new Button();
        btn.ID = "btn" + ControlCounter.ToString();
        btn.Width = Unit.Percentage(98);
        btn.CssClass = "button1";
        btn.Enabled = false;
        btn.Text = "...";
        btn.ToolTip = "Bill reference";
        btn.Attributes.Add("onclick", "return Transfervalue('" + ControlCounter + "');");
        //btn.OnClientClick=  "alert('abc')";
        HiddenField hidbillamt = new HiddenField();
        hidbillamt.ID = "hidbillamt" + ControlCounter.ToString();

        htcell5.Controls.Add(btn);
        htcell5.Controls.Add(hidbillamt);
        LstHidAmt.Add(hidbillamt.ID);
        LstBtn.Add(btn.ID);


        HtmlTableCell htcell6 = new HtmlTableCell();
        htcell6.ID = "htcell6" + ControlCounter.ToString();
        htcell6.Width = "20%";
        htcell6.VAlign = "Top";
        TextBox txtBalance = new TextBox();
        txtBalance.ID = "txtBalance" + ControlCounter.ToString();
        txtBalance.Width = Unit.Percentage(98);
        txtBalance.CssClass = "inputnumber";
        txtBalance.Enabled = false;
        txtBalance.ToolTip = "Ledger Balance";
        htcell6.Controls.Add(txtBalance);
        LstBalance.Add(txtBalance.ID);

        htrow.Cells.Add(htcell1);
        htrow.Cells.Add(htcell2);
        htrow.Cells.Add(htcell3);
        htrow.Cells.Add(htcell4);
        htrow.Cells.Add(htcell5);
        htrow.Cells.Add(htcell6);
        tblVouEntry.Rows.Add(htrow);

        ViewState["LstList"] = LstList;
        ViewState["LstLedgerName"] = LstLedgerName;
        ViewState["LstDrCr"] = LstDrCr;
        ViewState["LstDebit"] = LstDebit;
        ViewState["LstCredit"] = LstCredit;
        ViewState["LstBtn"] = LstBtn;
        ViewState["LstBalance"] = LstBalance;
        hidControl.Value = ControlCounter.ToString();
        BindLedger_ForDebitAndCredit(ddlDrCr.SelectedIndex, ControlCounter);
        // }
    }
    protected void DeleteLastRow()
    {
        int rowCount = Convert.ToInt32(hidControl.Value);
        int rowIndex = rowCount;
        for (int i = 0; i < tblVouEntry.Rows.Count; i++)
        {
            if (i > 2)
            {

                if (rowCount == i)
                {
                    tblVouEntry.Rows.RemoveAt(rowCount);
                    rowIndex = rowCount - 1;
                    LstList.RemoveAt(rowCount - 3);
                    LstLedgerName.RemoveAt(rowCount - 3);
                    LstDrCr.RemoveAt(rowCount - 3);
                    LstDebit.RemoveAt(rowCount - 3);
                    LstCredit.RemoveAt(rowCount - 3);
                    LstBalance.RemoveAt(rowCount - 3);
                    ViewState["LstList"] = LstList;
                    ViewState["LstLedgerName"] = LstLedgerName;
                    ViewState["LstDrCr"] = LstDrCr;
                    ViewState["LstDebit"] = LstDebit;
                    ViewState["LstCredit"] = LstCredit;
                    ViewState["LstBalance"] = LstBalance;
                    hidControl.Value = rowIndex.ToString();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "SetZeroOnBlurDebit(); SetZeroOnBlurCredit();", true);
                }
            }
        }
    }
    protected void ddlLedger_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        string ddlId = ddl.ID.ToString().Substring(9);
        int rowNo = Convert.ToInt32(ddlId);
        TextBox txtBalance = (TextBox)tblVouEntry.Rows[rowNo].FindControl("txtBalance" + rowNo);
        Button btn = (Button)tblVouEntry.Rows[rowNo].FindControl("btn" + rowNo);
        if (ddl.SelectedValue != "-1")
        {
            SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@Lid",ddl.SelectedValue),
                                        new SqlParameter("@Finyear",Session["FINYEAR"].ToString())
                                    };
            DataTable DT = DU.getdatausingprocedure("USP_ACC_GetLedgerCurrentBalance", sparam);
            if (DT.Rows.Count > 0)
            {
                txtBalance.Text = Convert.ToDouble(DT.Rows[0]["ClosingBal"].ToString()).ToString("N2") + " " + DT.Rows[0]["DebitCredit"].ToString();
            }
        }
        if (ddl.SelectedValue != "")
        {
            bool IsDrCr = false;
            DataTable dt = DU.getdatausingprocedure("usp_acc_GetledgerbaseonDebtorCreditor");

            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (ddl.SelectedValue == dt.Rows[i]["Lid"].ToString())
                    {
                        IsDrCr = true;
                        // btn.Visible = true;
                        break;
                    }
                }
            }
            if (IsDrCr == true)
            {
                btn.Enabled = true;

            }
            else
            {
                btn.Enabled = false;
            }
        }

    }
    protected void BindLedger_ForDebitAndCredit(int CreditOrDebit, int RowNo)
    {
        SqlParameter[] sparam =
                                {
                                    new SqlParameter("@CreditOrDebit",CreditOrDebit.ToString())
                                };
        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetLedgerForSaleTransaction", sparam);
        if (DT.Rows.Count > 0)
        {
            DropDownList ddlLedger = (DropDownList)tblVouEntry.Rows[RowNo].FindControl("ddlLedger" + RowNo);
            ddlLedger.DataSource = DT;
            ddlLedger.DataTextField = "LNAME";
            ddlLedger.DataValueField = "LID";
            ddlLedger.DataBind();
            ddlLedger.Items.Insert(0, new ListItem("", "-1"));
        }
    }
    protected void ddlDrCr_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        string ddlid = ddl.ID.ToString().Substring(7);
        int rowIndex = Convert.ToInt32(ddlid.ToString());
        TextBox txtDebit = (TextBox)tblVouEntry.Rows[rowIndex].FindControl("txtDebit" + rowIndex);
        TextBox txtCredit = (TextBox)tblVouEntry.Rows[rowIndex].FindControl("txtCredit" + rowIndex);
        if (ddl.SelectedIndex == 0)
        {
            BindLedger_ForDebitAndCredit(ddl.SelectedIndex, rowIndex);
            txtDebit.Enabled = true;
            txtDebit.Text = "0.00";
            txtCredit.Text = "";
            txtCredit.Enabled = false;
        }
        else if (ddl.SelectedIndex == 1)
        {
            BindLedger_ForDebitAndCredit(ddl.SelectedIndex, rowIndex);
            txtDebit.Text = "";
            txtDebit.Enabled = false;
            txtCredit.Enabled = true;
            txtCredit.Text = "0.00";
        }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "SetZeroOnBlurDebit(); SetZeroOnBlurCredit();", true);
    }
    protected void btnClose_Click(object sender, EventArgs e)
    {
        Response.Redirect("VoucherEntry.aspx");
    }
    protected void BindVoucherNumber()
    {
        strsql = "Select PREFIX,SUFFIX From ACC_TRANSETTINGDETAILS Where TypeId='10'";
        DataTable DTPrefix = DU.getdata(strsql);
        if (DTPrefix.Rows.Count > 0)
        {
            if (DTPrefix.Rows[0]["Prefix"].ToString() != string.Empty)
            {
                txtPrefix.Visible = true;
                txtPrefix.Text = DTPrefix.Rows[0]["Prefix"].ToString();
            }
            if (DTPrefix.Rows[0]["SUFFIX"].ToString() != string.Empty)
            {
                txtSuffix.Visible = true;
                txtSuffix.Text = DTPrefix.Rows[0]["SUFFIX"].ToString();
            }
        }
        SqlParameter[] sparam =
                                {
                                    new SqlParameter("@TransactionTypeID","10"),
                                    new SqlParameter("@FinYear",Session["FINYEAR"].ToString())
                                };
        DataTable DTVouNumber = DU.getdatausingprocedure("USP_ACC_GetVoucherNumbers", sparam);
        if (DTVouNumber.Rows.Count > 0)
        {
            txtVouNo.Text = (Convert.ToDouble(DTVouNumber.Rows[0]["TransactionNumber"]) + 1).ToString();
        }
        else
        {
            txtVouNo.Text = "1";
        }


    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (validation() == true)
            {
                
                using (TransactionScope scope = new TransactionScope())
                {
                    SaveVoucherMain();
                    scope.Complete();
                   
                }
                //Response.Redirect("Sale.aspx?status=save");
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }

    protected void SaveVoucherMain()
    {
        try
        {
        string vouDate = string.Empty;
        if (txtDate.Text != string.Empty)
        {
            string[] str = txtDate.Text.ToString().Split('/');
            vouDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
        }
        else
        {
            vouDate = string.Format("{0:MM/dd/yyyy", Convert.ToDateTime(System.DateTime.Now)).ToString();
        }
        string finYear = Session["FINYEAR"].ToString();

        if (finYear != string.Empty)
        {

            SqlParameter[] sparam =
                                        {                                            
                                            new SqlParameter("@TransactionTypeID","10"),
                                            new SqlParameter("@TransactionNumber",txtVouNo.Text.Trim()),
                                            new SqlParameter("@FinYear",finYear.ToString()),
                                            new SqlParameter("@ReferenceNumber",txtVouNo.Text.Trim()),
                                            new SqlParameter("@IsCashVoucher",radioCashCredit.SelectedValue),
                                            new SqlParameter("@TransactionDate",vouDate),
                                            new SqlParameter("@Narration",txtNarration.Text.Trim()),
                                            new SqlParameter("@CreditDays",txtCreditDays.Text.Trim()),                                            
                                            new SqlParameter("@CreatedBy",Session["Username"].ToString()),
                                            new SqlParameter("@IsCancelled","0"),
                                            new SqlParameter("@CostCentreClassID","0")
                                        };
            int result = DU.executeprocedure("USP_ACC_SaveTransaction", sparam);
            if (result > 0)
            {
                strsql = "Select Ident_current('ACC_VOUCHERS') as VouId";
                DataTable DT1 = DU.getdata(strsql);
                if (DT1.Rows.Count > 0)
                {
                    SaveVoucherDetials(DT1.Rows[0]["VouId"].ToString());
                }
            }
        }
          }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void SaveVoucherDetials(string strVoiId)
    {
        try
        {
        if (strVoiId.ToString() != string.Empty)
        {
            string strRefDate = string.Empty;
            if (txtDate.Text != string.Empty)
            {
                string[] str = txtDate.Text.ToString().Split('/');
                strRefDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            else
            {
                strRefDate = string.Format("{0:MM/dd/yyyy", Convert.ToDateTime(System.DateTime.Now)).ToString();
            }
            for (int i = 1; i < tblVouEntry.Rows.Count; i++)
            {
                int result = 0;
                DropDownList ddlDrCr = (DropDownList)tblVouEntry.Rows[i].FindControl("ddlDrCr" + i);
                DropDownList ddlLedger = (DropDownList)tblVouEntry.Rows[i].FindControl("ddlLedger" + i);
                TextBox txtDebit = (TextBox)tblVouEntry.Rows[i].FindControl("txtDebit" + i);
                TextBox txtCredit = (TextBox)tblVouEntry.Rows[i].FindControl("txtCredit" + i);

                if (ddlDrCr.SelectedIndex == 0)
                {
                    if (Convert.ToDouble(txtDebit.Text) > 0)
                    {
                        double DebitAmt = 0 - Convert.ToDouble(txtDebit.Text.ToString());
                        SqlParameter[] sparam =
                                                {                                                    
                                                    new SqlParameter("@TransactionId",strVoiId.ToString()),
                                                    new SqlParameter("@LedgerId",ddlLedger.SelectedValue),
                                                    new SqlParameter("@Amount",DebitAmt.ToString()),
                                                    new SqlParameter("@IsReconciled","0"),
                                                };
                        result = DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                        if (result > 0)
                        {
                            strsql = "Select Ident_Current('ACC_VOUDETAILS') as VouSerial";
                            DataTable DT = DU.getdata(strsql);
                            string vouserial = DT.Rows[0]["VouSerial"].ToString();
                            SaveRefdetail(vouserial);
                            //    if (DT.Rows.Count > 0)
                            //    {
                            //        SqlParameter[] sparam1 = {
                            //                                    new SqlParameter("@ReferenceSerial","0"),
                            //                                    new SqlParameter("@ParentReference","0"),
                            //                                    new SqlParameter("@TransactionSerial",DT.Rows[0]["VouSerial"].ToString()),
                            //                                    new SqlParameter("@ReferenceType","3"),
                            //                                    new SqlParameter("@Reference",""),
                            //                                    new SqlParameter("@ReferenceDate",strRefDate),
                            //                                    new SqlParameter("@CreditDays","0"),
                            //                                    new SqlParameter("@ReferenceAmount",DebitAmt),
                            //                                    new SqlParameter("@IsTDSDeducted","0")
                            //                                    };
                            //       DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam1);
                            //    }

                        }
                    }
                }

                else if (ddlDrCr.SelectedIndex == 1)
                {
                    if (Convert.ToDouble(txtCredit.Text) > 0)
                    {
                        SqlParameter[] sparam =
                                                {                                                    
                                                    new SqlParameter("@TransactionId",strVoiId.ToString()),
                                                    new SqlParameter("@LedgerId",ddlLedger.SelectedValue),
                                                    new SqlParameter("@Amount",txtCredit.Text.Trim()),
                                                    new SqlParameter("@IsReconciled","0"),
                                                };
                        result = DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                    }
                }
            }
        }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void SaveRefdetail(string vouserial)
    {
        try
        {
            for (int i = 1; i < tblVouEntry.Rows.Count; i++)
            {
                HiddenField hidbillamt = (HiddenField)tblVouEntry.Rows[i].FindControl("hidbillamt" + i);
                if (hidbillamt.Value != "")
                {
                    string[] dramt = hidbillamt.Value.Split(':');
                    if (dramt.Length > 1)
                    {
                        Double totalDramt =0;
                        Double totalCramt =0;
                        string[] drcelltxtamt = dramt[0].Split('|');
                        string[] celltype = dramt[1].Split('|');
                        string[] DrCrcell = dramt[2].Split('|');
                        string[] SelectTxtParticular = dramt[4].Split('-');
                        string[] SelectDdlParticular = dramt[3].Split('|');
                        string[] SelectDate = dramt[5].Split('|');
                        string[] SelectDdlparticulartext = dramt[6].Split(',');
                        string[] SelectedCredit = dramt[7].Split('|');
                        //lblMsg.Text = dramt[7].ToString();
                       
                        for (int j = 0; j < drcelltxtamt.Length - 1; j++) // drtxramt.Length = 3
                        {
                            string dbamt = drcelltxtamt[j].ToString();
                            string type = celltype[j].ToString();
                            string ddlDrCrBill = DrCrcell[j].ToString();
                            string TxtParticular = SelectTxtParticular[j].ToString();
                            string DdlParticular = SelectDdlParticular[j].ToString();
                            string DdlParticulartext = SelectDdlparticulartext[j].ToString();
                            string Date = SelectDate[j].ToString();
                            string CreditAmt = SelectedCredit[j].ToString();
                            //lblMsg.Text += Server.HtmlEncode(drcelltxtamt[j].ToString());
                            if (Date.Length > 0)
                            {
                                string[] datearr = Date.Split('/');
                                string dateformat = datearr[1].ToString() + "/" + datearr[0].ToString() + "/" + datearr[2].ToString();
                                double DebitAmt = 0;
                                if (dbamt.Length>0)
                                {
                                 DebitAmt = Convert.ToDouble(dbamt.Trim());
                                }
                               totalDramt += DebitAmt;
                               double CrAmt = 0;
                               if (CreditAmt.Length > 0)
                               {
                                   CrAmt = Convert.ToDouble(CreditAmt.Trim());
                               }
                               totalCramt += CrAmt;
                               if (ddlDrCrBill.ToString() == "1")
                               {
                                   double debitValue = 0 - totalDramt;
                                   if (type == "1" || type == "3")
                                   {
                                       SqlParameter[] sparam1 = {
                                       new SqlParameter("@ReferenceSerial","0"),
                                        new SqlParameter("@ParentReference",DdlParticular),
                                        new SqlParameter("@TransactionSerial",vouserial),
                                        new SqlParameter("@ReferenceType",type),
                                        new SqlParameter("@Reference",TxtParticular),
                                        new SqlParameter("@ReferenceDate",dateformat),
                                        new SqlParameter("@CreditDays","0"),
                                        new SqlParameter("@ReferenceAmount",debitValue),
                                        new SqlParameter("@IsTDSDeducted","0")
                                        };
                                      DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam1);
                                   }
                               }
                               else if (ddlDrCrBill.ToString() == "2")
                               {
                                   if (type == "2")
                                   {
                                       SqlParameter[] sparam1 = {
                                        new SqlParameter("@ReferenceSerial","0"),
                                        new SqlParameter("@ParentReference",DdlParticular),
                                        new SqlParameter("@TransactionSerial",vouserial),
                                        new SqlParameter("@ReferenceType",type),
                                        new SqlParameter("@Reference",DdlParticulartext),
                                        new SqlParameter("@ReferenceDate",dateformat),
                                        new SqlParameter("@CreditDays","0"),
                                        new SqlParameter("@ReferenceAmount",totalCramt),
                                        new SqlParameter("@IsTDSDeducted","0")
                                        };
                                       DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam1);
                                   }
                               }
                            }

                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected bool validation()
    {
        bool Isvalid = true;
        int ddlcount = 0;
        for (int i = 1; i < tblVouEntry.Rows.Count; i++)
        {
            HiddenField hidbillamt = (HiddenField)tblVouEntry.Rows[i].FindControl("hidbillamt" + i);
            DropDownList ddlLedger = (DropDownList)tblVouEntry.Rows[i].FindControl("ddlLedger" + i);
            TextBox txtDebit = (TextBox)tblVouEntry.Rows[i].FindControl("txtDebit" + i);
            TextBox txtCredit = (TextBox)tblVouEntry.Rows[i].FindControl("txtCredit" + i);
            Button btn = (Button)tblVouEntry.Rows[i].FindControl("btn" + i);
            
             if (ddlLedger.SelectedValue != "")
             {
                // bool IsDrCr = false;
                 DataTable dt = DU.getdatausingprocedure("usp_ledgerbaseonDebtorCreditor");
                 if (dt.Rows.Count > 0)
                 {
                     for (int j = 0; j < dt.Rows.Count; j++)
                     {
                         if(ddlLedger.SelectedValue == dt.Rows[j]["Lid"].ToString())
                         {
                             ddlcount++;
                             if (ddlcount == 2)
                             {
                                 Isvalid = false;
                                 lblMsg.Text = "Dublicate Sundry Creditor";
                                 break;
                             }
                             else
                             {
                                 if (hidbillamt.Value != "")
                                 {
                                     Isvalid = true;
                                 }
                                 else
                                 {
                                     lblMsg.Text = "bill Reference not be blank";
                                     Isvalid = false;
                                     break;
                                 }
                             }
                         }
                     }
                 }
             }
             if (Isvalid == false)
             {
                 break;
             }
        }
        return Isvalid;
    }
}

   // [WebMethod]
    //public static string MyMethod(string name)
    //{
    //    return "Hello " + name;
    //}


                    
